package com.zhilianbao.leyaogo.ui.fragment.goodscategory;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.convenientlog.CLog;
import com.bql.fragmentation.ControllerFragment;
import com.bql.statetypelayout.AnimationStateTypeLayout;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.CategoryApi;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.model.response.category.CategoryInfo;
import com.zhilianbao.leyaogo.ui.activity.me.myorder.RefundActivity;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseOkHttpFragment;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.marqueeview.MarqueeView;
import com.zhilianbao.okhttputils.request.BaseRequest;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static android.widget.RelativeLayout.CENTER_IN_PARENT;


/**
 * 商品分类
 * Created by gyt on 2016/11/1
 */
public class GoodsCategoryFragment extends BaseOkHttpFragment {


    @BindView(R.id.tv_hint_search)
    TextView mTvHintSearch;
    @BindView(R.id.fl_container)
    RelativeLayout mRlcontainer;
    @BindView(R.id.stateLayout)
    AnimationStateTypeLayout mStateLayout;
    private LayoutInflater inflater;
    private LinearLayout loadingStateLinearLayout;
    private View view;
    private ImageView mLoadingView;
    private AnimationDrawable loadingDrawable;
    private MarqueeView loadingTextView;
    private RelativeLayout.LayoutParams layoutParams;
    private boolean mInit;
    private List<String> hotList = new ArrayList<>();

    public static GoodsCategoryFragment getInstance() {
        GoodsCategoryFragment fragment = new GoodsCategoryFragment();
        return fragment;
    }

    @Override
    protected void initToolbarHere() {
        bindToolbar();
        mTvHintSearch.setText("");
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {

    }

    private void getGoodsList() {
        CLog.i("getGoodsList=================================");
        CategoryApi.getClassifyList(mActivity, Utils.getSupplierId() /*1237*/, new LoadingViewCallback<List<CategoryInfo>>(mActivity, getView(), false) {

            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                showLoadingView();
            }

            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                getGoodsList();
                mStateLayout.hideErrorView();
                mStateLayout.hideEmptyView();
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_GET_SHOPPING_CART_NUM));
            }

            @Override
            public boolean isShowLoading() {
                return false;
            }

            @Override
            public boolean showEmptyButton() {
                return true;
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                hideLoadingView();
            }

            @Override
            public void onResultSuccess(List<CategoryInfo> categoryLists, @Nullable Response response, LoadingViewCallback callback) {
                CategoryListFragment categoryListFragment = CategoryListFragment.getInstance(categoryLists);
                loadRootFragment(R.id.fl_menu_container, categoryListFragment);
                if (categoryLists.size() != 0) {
                    int type = categoryLists.get(0).getType();
                    int classifyId = categoryLists.get(0).getClassifyId();
                    // 活动Id，type = 0，使用classifyId；type = 1，使用activityId
                    int activityId = categoryLists.get(0).getActivityId();
                    replaceLoadRootFragment(R.id.fl_content_container, GoodsListFragment.getInstance(type, type == 0 ? classifyId : activityId), false);
                } else {
                    hideLoadingView();
                    callback.showEmpty();
                }
            }
        });
    }


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_goods_category;
    }

    public void showLoadingView() {
        CLog.d("showLoadingView");
        if (loadingStateLinearLayout == null) {
            initLoadingView();
        }
        if (loadingStateLinearLayout != null && loadingStateLinearLayout.getVisibility() == GONE) {
            loadingStateLinearLayout.setVisibility(VISIBLE);
        }

        if (loadingTextView != null && !loadingTextView.isFlipping()) {
            loadingTextView.start();
        }
    }

    public void hideLoadingView() {
        if (loadingStateLinearLayout != null) {
            loadingStateLinearLayout.setVisibility(GONE);
        }
        if (loadingTextView != null && loadingTextView.isFlipping()) {
            loadingTextView.stop();
        }
    }


    /**
     * 替换加载 内容Fragment
     *
     * @param fragment
     */
    public void switchContentFragment(GoodsListFragment fragment) {
        ControllerFragment ControllerFragment = findChildFragment(GoodsListFragment.class);
        if (ControllerFragment != null) {
            ControllerFragment.replaceFragment(fragment, false);
        }
    }

    @OnClick(R.id.toolbar)
    public void onClick(View view) {

        startActivity(new Intent(mActivity, RefundActivity.class));
//        Bundle bundle = new Bundle();
//        bundle.putSerializable(IntentConfig.HOT_SEARCH_LIST, (Serializable) hotList);
//        Utils.startActivity(mActivity, SearchActivity.class, bundle);
    }

    @Override
    protected boolean lazyLoadMode() {
        return true;
    }

    @Override
    protected void initLazyViewsAndEvents(@Nullable Bundle savedInstanceState) {
        super.initLazyViewsAndEvents(savedInstanceState);
        // 初始化完成，
        mInit = true;
        initLoadingView();
        getGoodsList();
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        // 选择商铺后改变数据
        if (eventManager.getEventCode() == LeEventCode.MSG_CODE_SELECT_OPERATOR) {
            if (mInit) {
                getGoodsList();
            }
        } else if (eventManager.getEventCode() == LeEventCode.MSG_CODE_HOME_DATA_REFRESH) {
            hotList = (List<String>) eventManager.getData();
            mTvHintSearch.setText(hotList.get(0));
        }
    }

    /**
     * 初始化中间的Loadingview
     */
    private void initLoadingView() {
        if (loadingStateLinearLayout == null) {
            inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            view = inflater.inflate(R.layout.view_loding_category, null);
            if (view == null) {
                throw new NullPointerException(
                        "Loading view is null! Have you specified a loading view in your layout xml file?");
            }
            loadingStateLinearLayout = (LinearLayout) view.findViewById(R.id.loadingViewLinearLayout);

            mLoadingView = (ImageView) view.findViewById(R.id.iv_loading);
            mLoadingView.setBackgroundResource(R.drawable.loading);
            loadingDrawable = (AnimationDrawable) mLoadingView.getBackground();
            loadingDrawable.mutate();
            loadingDrawable.start();
            //            loadingStateContentTextView = (TextView) view.findViewById(loadingStateContentTextView);
            loadingTextView = (MarqueeView) view.findViewById(R.id.loading_textView);
            List<String> loadingList = new ArrayList<>();
            loadingList.add(mActivity.getString(com.bql.statetypelayout.R.string.loading_1));
            loadingList.add(mActivity.getString(com.bql.statetypelayout.R.string.loading_2));
            loadingList.add(mActivity.getString(com.bql.statetypelayout.R.string.loading_3));
            loadingList.add(mActivity.getString(com.bql.statetypelayout.R.string.loading_4));
            loadingTextView.setNotices(loadingList);

            layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(CENTER_IN_PARENT);
            mRlcontainer.addView(loadingStateLinearLayout, layoutParams);
        }
        loadingStateLinearLayout.setVisibility(GONE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (loadingDrawable != null) {
            loadingDrawable.stop();
            loadingDrawable = null;
        }
        if (loadingTextView != null && loadingTextView.isFlipping()) {
            loadingTextView.stop();
            loadingTextView = null;
        }
    }
}
